package com.cn.kehong.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.kehong.api.IFileInfoService;
import com.cn.kehong.api.IWxUserService;
import com.cn.kehong.conf.Config;
import com.cn.kehong.dao.LoginMapper;
import com.cn.kehong.dao.WxUserMapper;
import com.cn.kehong.domain.Login;
import com.cn.kehong.domain.WxUser;
import com.cn.kehong.domain.WxUserExample;
import com.cn.kehong.utils.*;
import com.cn.kehong.utils.msgSend.HttpClientUtil;
import com.cn.kehong.utils.msgSend.JsonReqClient;
import com.google.common.collect.Maps;
import net.sourceforge.tess4j.Tesseract;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class WxUserServiceImpl implements IWxUserService {

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private LoginMapper loginMapper;


    @Autowired
    Config config;

    @Autowired
    private IFileInfoService fileInfoService;


    @Override
    public List<WxUser> queryWxUserList(QueryForm queryForm) throws Exception {

        return null;
    }

    @Override
    public List<WxUser> queryWxUserSelectList() throws Exception {
        WxUserExample example = new WxUserExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS);
        return wxUserMapper.selectByExample(example);
    }

    @Override
    public Map<String, String> queryWxUserMap() throws Exception {
        List<WxUser> list = this.queryWxUserSelectList();
        Map<String, String> map = Maps.newHashMap();
        for (WxUser wxUser : list) {
            map.put(wxUser.getId(), wxUser.getWxName());
        }
        return map;
    }

    @Override
    public String updateWxUserInfo(WxUser wxUser) throws Exception {
        if(StringUtils.isEmpty(wxUser.getId())){
            return "缺少主键Id";
        }
        if(StringUtils.isEmpty(wxUser.getWxName())){
            return "昵称不能为空";
        }
        WxUserExample example = new WxUserExample();
        WxUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(wxUser.getId());
        WxUser update= new WxUser();
        update.setWxName(wxUser.getWxName());
        int count = wxUserMapper.updateByExampleSelective(update,example);
        List<WxUser> list = wxUserMapper.selectByExample(example);
        if (count < 1) {
            return "更新失败！";
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public WxUser queryWxUserById(String id) throws Exception {
        WxUserExample example = new WxUserExample();
        WxUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        List<WxUser> list = wxUserMapper.selectByExample(example);
        if (CollectionsUtil.isEmpty(list) || list.size() != 1) {
            throw new Exception("queryWxUserById error:" + list.size());
        }
        return list.get(0);
    }

    @Override
    public String addWxUser(WxUser login) throws Exception {
        int count = this.countWxUser(login.getWxPhone(), "");
        if (count > 0) {
            throw new Exception("手机已经注册，请重新修改！");
        }
        String id = CommonUtil.generateRandomNum("wxlogin-");
        login.setId(id);
        int addCount = wxUserMapper.insertSelective(login);
        return CommonUtil.outStr(addCount);
    }

    @Override
    public String delWxUser(QueryForm queryForm) throws Exception {
        List<String> ids = queryForm.getIds();
        if (CollectionsUtil.isEmpty(ids)) {
            throw new Exception("ids 为空!");
        }
        WxUserExample example = new WxUserExample();
        example.createCriteria().andIdIn(ids);
        WxUser login = new WxUser();
        login.setStatus(Constants.DEL_STATUS);
        int count = wxUserMapper.updateByExampleSelective(login, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateWxUser(WxUser login) throws Exception {
        String id = login.getId();
        int count = this.countWxUser(login.getWxPhone(), id);
        if (count > 0) {
            throw new Exception("手机已经注册，请重新修改！");
        }
        WxUserExample example = new WxUserExample();
        example.createCriteria().andIdEqualTo(id);
        int updateCount = wxUserMapper.updateByExampleSelective(login, example);
        return CommonUtil.outStr(updateCount);
    }

    @Override
    public String updateWxUserStatus(WxUser login) throws Exception {
        String id = login.getId();
        if (StringUtils.isEmpty(id)) {
            throw new Exception("updateWxUserStatus id null！");
        }
        WxUserExample example = new WxUserExample();
        example.createCriteria().andIdEqualTo(id);
        int count = wxUserMapper.updateByExampleSelective(login, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public int countWxUser(String loginAccount, String userId) throws Exception {
        WxUserExample example = new WxUserExample();
        WxUserExample.Criteria criteria = example.createCriteria();
        criteria.andWxPhoneEqualTo(loginAccount);
        if (StringUtils.isNotBlank(userId)) {
            criteria.andIdNotEqualTo(userId);
        }
        int count = wxUserMapper.countByExample(example);
        return count;
    }

    @Override
    public WxUser doLogin(WxUser login) throws Exception {

        return null;
    }

    @Override
    public WxUser getWxUserByOpenId(String openId) throws Exception {
        WxUserExample example = new WxUserExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andOpenIdEqualTo(openId);
        List<WxUser> wxUsers = wxUserMapper.selectByExample(example);
        if(wxUsers.size() > 1){
            return null;
        }
        if(CollectionUtils.isEmpty(wxUsers)){
            return new WxUser();
        }
        return wxUsers.get(0);
    }

    @Override
    public String sendCode(String phone) throws Exception {
        JsonReqClient jsonReqClient = new JsonReqClient();
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
        String param = code + ",120";
        String result = jsonReqClient.sendSms(config.sid, config.token, config.appid, config.templateId, param, phone, "");
        System.out.println(result);
        redisTemplate.opsForValue().set(phone, code, 120, TimeUnit.SECONDS);
        return code;
    }

    @Override
    public JSONObject updateOrGetPhoneNum(String code,String openId) throws Exception {
        if(StringUtils.isEmpty(openId)){
            JSONObject jsRes = new JSONObject();
            jsRes.put("errcode",-1);
            jsRes.put("errmsg","openId is null!");
            jsRes.put("success",false);
            return jsRes;
        }
        WxUser wxUser = getWxUserByOpenId(openId);
        if(null == wxUser){
            JSONObject jsRes = new JSONObject();
            jsRes.put("errcode",-1);
            jsRes.put("success",false);
            jsRes.put("errmsg","wxUser is error!");
            return jsRes;
        }

        String token = this.getAccessToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
//        jsonObject.put("access_token", token);
        String body = jsonObject.toJSONString();
        System.out.println("-----:token-----"+token);
        String result = HttpClientUtil.postJson("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token + "&code=" + code, body, null);
        JSONObject res = JSON.parseObject(result);

        String userId = wxUser.getId();
        String phonePhone = wxUser.getWxPhone();
        String existPhone = res.getJSONObject("phone_info").getString("phoneNumber");

        List<Login> logins = loginMapper.selectUserInfoByPhone(existPhone);
        if(!CollectionUtils.isEmpty(logins) && logins.size() == 1){
            res.getJSONObject("phone_info").put("appUserType",logins.get(0).getAppUserType());
        }
        if(StringUtils.isEmpty(userId)){
            WxUser add = new WxUser();
            userId = CommonUtil.generateRandomNum("wxuser-");
            add.setId(userId);
            add.setWxPhone(existPhone);
            if(!CollectionUtils.isEmpty(logins)){
                add.setWxName(logins.get(0).getUserName());
            }else{
                add.setWxName("微信用户"+new Random().nextInt(9999));
            }
            add.setOpenId(openId);
            String addRes = this.addWxUser(add);
            if(StringUtils.isNotEmpty(addRes)){
                JSONObject jsRes = new JSONObject();
                jsRes.put("success",false);
                jsRes.put("errcode",-1);
                jsRes.put("errmsg",addRes);
                return jsRes;
            }
            res.getJSONObject("phone_info").put("nickname","微信用户");
            res.getJSONObject("phone_info").put("headImg","");
            res.getJSONObject("phone_info").put("userId",userId);
            return res;
        }else if(!StringUtils.equals(phonePhone,existPhone)){
            WxUser update = new WxUser();
            update.setId(wxUser.getId());
            update.setWxPhone(existPhone);
            update.setOpenId(openId);
            String updateRes = this.updateWxUser(update);
            if(StringUtils.isNotEmpty(updateRes)){
                JSONObject jsRes = new JSONObject();
                jsRes.put("errcode",-1);
                jsRes.put("success",false);
                jsRes.put("errmsg",updateRes);
                return jsRes;
            }
        }
        res.getJSONObject("phone_info").put("wxName", wxUser.getWxName());
        res.getJSONObject("phone_info").put("headImg",wxUser.getWxAttrUrl());
        res.getJSONObject("phone_info").put("userId",userId);
        return res;
    }

    @Override
    public JSONObject getWxUserDetail(String userId) throws Exception {
        JSONObject jsRes = new JSONObject();
        jsRes.put("success",false);
        if(StringUtils.isEmpty(userId)){
            jsRes.put("errcode",-1);
            jsRes.put("errmsg","缺少id参数！");
            return jsRes;
        }
        WxUser wxUser = wxUserMapper.selectByPrimaryId(userId);
        if(null == wxUser){
            jsRes.put("errcode",-1);
            jsRes.put("errmsg","未查询到用户！");
            return jsRes;
        }
        List<Login> logins = loginMapper.selectUserInfoByPhone(wxUser.getWxPhone());
        if(!CollectionUtils.isEmpty(logins)){
            wxUser.setAppUserType(logins.get(0).getAppUserType());
        }
        jsRes.put("wxUser",wxUser);
        return jsRes;
    }

    private String getAccessToken() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appid", "wx9a241243435bfc6b");
        jsonObject.put("secret", "2a4bc056e9955bf2881cf5f53b087379");
        String body = jsonObject.toJSONString();
        String result = HttpClientUtil.postJson("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9a241243435bfc6b&secret=2a4bc056e9955bf2881cf5f53b087379", body, null);
        System.out.println("-----------getAccessToken----------------:" + result);
        JSONObject res = JSON.parseObject(result);
        if (result == null || null == res) {
            System.out.println("获取token 失败");
            return "";
        }
        String accessToken = res.getString("access_token");
        return accessToken;
    }

    @Override
    public String getWxOpenId(String code) throws Exception {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx9a241243435bfc6b" + "&secret=2a4bc056e9955bf2881cf5f53b087379" + "&js_code=" + code + "&grant_type=authorization_code";
        String analysis = HttpsUtil.httpRequest(url);
        if (StringUtils.isBlank(analysis)) {
            return "";
        }
        JSONObject jsonObject = JSON.parseObject(analysis);
        Object object = jsonObject.get("openid");
        if (object == null) {
            return "";
        }
        String openid = jsonObject.get("openid").toString();
        if (StringUtils.isBlank(openid)) {
            return "";
        }
        return openid;
    }

    @Override
    public String updateWxUserPassword(WxUser wxUser) throws Exception {

        return null;
    }

    @Override
    public WxUser updateWxUserImgById(WxUser wxUser) throws Exception {
        String id = wxUser.getId();
        if(StringUtils.isEmpty(id)){
            return null;
        }
        String wxAttrUrl = wxUser.getWxAttrUrl();
        if(StringUtils.isEmpty(wxAttrUrl)){
            return null;
        }
        String url = fileInfoService.addFileWithBlob(wxAttrUrl);
        if(StringUtils.isEmpty(url)){
            return null;
        }
        WxUser update = new WxUser();
        update.setWxAttrUrl(url);
        update.setId(id);
        int count = wxUserMapper.updateWxUserImageById(update);
        if(count < 0){
            return null;
        }
        wxUser.setWxAttrUrl(url);
        return wxUser;
    }


    public static void main(String args[]) throws Exception {
        File imageFile = new File("F:\\3.png");
        BufferedImage image = ImageIO.read(imageFile);
        // 图片预处理
        // ...
        // 文字识别
        Tesseract tesseract = new Tesseract();
        tesseract.setDatapath("F:\\tessdata-master");
        tesseract.setLanguage("chi_sim");
//        tesseract.setOcrEngineMode(1);
//        tesseract.setPageSegMode(6);
        String result = tesseract.doOCR(image);
        // 输出识别结果
        System.out.println(result);
    }
}
